'use strict'
const Koa = require('koa');
const App = new Koa();
const fs= require('fs');
const router = require('koa-router')();
const Cors = require('koa-cors');
const path = require('path');
const LRU = require('lru-cache');
const Static = require('koa-static');
const favicon = require('koa-favicon');
const {createBundleRenderer} = require('vue-server-renderer');
const resolve = file =>path.resolve(__dirname,file);


//使用环境
const isContext = process.env.NODE_ENV === "work"

function createRenderer (bundle, options) {
	
  return createBundleRenderer(bundle, Object.assign(options, {
		//设置高速缓存
		cache: LRU({
      max: 1000,
      maxAge: 1000 * 60 * 15
    }),
		//只有当vue服务器-渲染器与npm相关时才需要这样做
		basedir: resolve('../webBloger'),
		runInNewContext: false
	}))
}

let renderer
let readyPromise
const templatePath = resolve('../app/index.html')

if(isContext){
	//work环境
	//从fs 读取的文件 创建服务器渲染器
	const template = fs.readFileSync(templatePath, 'utf-8');//读取模板文件
	const bundle = require('../webBloger/vue-ssr-server-bundle.json');
	const clientManifest = require('../webBloger/vue-ssr-client-manifest.json');
	 renderer = createRenderer (bundle, {
    template,
    clientManifest
  })
}else{
	//使用热更新
	 readyPromise = require('../webpack/setup-dev-server')( 
    App,
    templatePath,
    (bundle, options) => {
      renderer = createRenderer(bundle, options)
    }
  )
}

//app.use(Static(path.resolve(__dirname, '../webBloger')))

async function render (ctx, next) {
	
  let context = {url: ctx.url}
  
  let html = await new Promise((resolve, reject) => {
    renderer.renderToString(context, (err, html) => {

      if (err) {
      	console.log('错误:',err)
        reject('404')
      } else {
        resolve(html)
      }
    })
  })
  ctx.body = html
}

App.use(Static('../webBloger'))

App.use(favicon(resolve('./Mazz.png')))

router.get('*', isContext ? render : async (ctx, next) => {
  ctx.set('Content-Type', 'text/html')
  await readyPromise.then(() => render(ctx, next))
})

App.use(router.routes()).use(router.allowedMethods())

App.listen(3301,()=>{
	console.log('服务启动，端口：3301')
})




